//
//  LiuComposeTextView.swift
//  LiuWeiBo
//
//  Created by 刘晓晨 on 2017/4/5.
//  Copyright © 2017年 刘晓晨. All rights reserved.
//

import UIKit

class LiuComposeTextView: UITextView {
    
   
    //懒加载控件
    fileprivate lazy var placeHolderLabel:UILabel = {
        let label = UILabel()
        label.text = "分享新鲜事..."
        label.textColor = UIColor.lightGray
        label.font = UIFont.systemFont(ofSize: 14)
        label.numberOfLines = 0
        return label
    }()
    
    //给外部的接口用来修改默认文字
    var placeHolder:String{
        set{
            placeHolderLabel.text = placeHolder
        } get {
            return placeHolderLabel.text ?? ""
        }
    }
    
    //修改textView的文字大小是默认文字也要修改,保证一致性
    override var font: UIFont? {
        didSet {
            if font != nil {
                placeHolderLabel.font = font
            }
        }
    }
    
    //判断外界是否在开始为textView赋值,如果有赋值,隐藏默认文字
    override var text: String! {
        didSet {
            if self.hasText {
                placeHolderLabel.isHidden = true
            }
        }
    }
    
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate func setupUI() {
        
        self.becomeFirstResponder()
        
        addSubview(placeHolderLabel)
        
        //自动布局
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 7))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
        
        //发送消息,来监听text的变化
        NotificationCenter.default.addObserver(self, selector: #selector(textChanged), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
        
        //监听表情按钮的点击
        NotificationCenter.default.addObserver(self, selector: #selector(emoticonButtonAction(noti:)), name: NSNotification.Name(rawValue: emoticonButtonNotification), object: nil)
        
        //监听删除按钮点击
        NotificationCenter.default.addObserver(self, selector: #selector(emoticonDeleteButtonAction), name: NSNotification.Name(emoticonDeleteButtonNotification), object: nil)
    }
    
    @objc fileprivate func textChanged() {
        placeHolderLabel.isHidden = self.hasText
    }
    
    //监听表情按钮点击
    @objc fileprivate func emoticonButtonAction(noti:Notification) {
        let emoticon:LiuEmoticonModel = noti.object as! LiuEmoticonModel
        
        //将数据显示到textView上
        attributeWithEnoticonModel(emoticon: emoticon)
    }
    
    //传递一个emoticonModel,返回一个富文本
    fileprivate func attributeWithEnoticonModel(emoticon:LiuEmoticonModel) {
        
        if emoticon.type == "0" {
            //是图片表情
            
            //记录上一次的富文本
            let lastAttributeStr:NSMutableAttributedString = NSMutableAttributedString(attributedString: attributedText)
            
            //选中位置
            var selectedrange = selectedRange
            
            //获取图片
            let image = UIImage(named: MainbundlePath! + emoticon.partPath!)
            
            //创建文本附件,存储图片
            let attachMent = LiuComposeTextAttachment()
            attachMent.image = image
            attachMent.emoticon = emoticon
            
            //设置富文本图片大小
            attachMent.bounds = CGRect(x: 0, y: -4, width: font!.lineHeight, height: font!.lineHeight)
            
            //根据文本附件创建富文本
            let attributeStr = NSAttributedString(attachment: attachMent)
            
//            //拼接富文本
//            lastAttributeStr.append(attributeStr)
            
            //替换选中的位置
            lastAttributeStr.replaceCharacters(in: selectedrange, with: attributeStr)
            
            //设置所有富文本的大小
            lastAttributeStr.addAttributes([NSFontAttributeName:font!], range: NSMakeRange(0, lastAttributeStr.length))
            
            //设置富文本
            attributedText = lastAttributeStr
            
            //光标放在替换后的位置
            selectedrange.location += 1
            selectedRange = NSMakeRange(selectedrange.location, 0)
            
            //主动调用文字改变的代理方法
            NotificationCenter.default.post(name: NSNotification.Name.UITextViewTextDidChange, object: nil)
            
            delegate?.textViewDidChange?(self)
            
        } else {
            //是emoji表情
            let emoji = (emoticon.code! as NSString).emoji()!
            insertText(emoji)
        }
        
        
    }
    
    //将带图片表情的富文本,转化成string字符串用于上传
    func getAllString() -> String {
        
        //创建一个可变字符串,等待接收遍历的字符串
        var sendMessage = ""
        
        //遍历富文本
        attributedText.enumerateAttributes(in: NSMakeRange(0, attributedText.length), options: []) { (info, range, _) in
            
            //判断infor是图片富文本还是普通富文本
            if let attachMent:LiuComposeTextAttachment = info["NSAttachment"] as? LiuComposeTextAttachment {
                //是图片富文本
                //获取chs拼接到后面
                let chs = attachMent.emoticon!.chs!
                sendMessage += chs
            } else {
                //是普通文本
                //获取富文本这个range对应的字符串
                let str = attributedText.attributedSubstring(from: range)
                
                //转化成string类型
                let subStr = str.string
                
                //追加到后面
                sendMessage += subStr
            }
        
    }
        return sendMessage
    }
    
    //监听删除按钮的点击
    @objc fileprivate func emoticonDeleteButtonAction() {
        deleteBackward()
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

}
